/**
 * Copyright (c) 2005-2009 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: SimpleHibernateDao.java 1005 2010-03-25 15:50:00Z calvinxiu $
 */
package net.uman.framework.modules.orm.hibernate;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import net.uman.entity.IdEntity;
import net.uman.framework.modules.objectpool.ObjectPool;
import net.uman.framework.modules.objectpool.ObjectPoolFactory;
import net.uman.framework.modules.orm.PropertyFilter;
import net.uman.framework.modules.utils.ApplicationContextProvider;
import net.uman.framework.modules.utils.ReflectionUtils;
import net.uman.framework.modules.utils.SqlHelper;

import org.hibernate.Criteria;
import org.hibernate.FlushMode;
import org.hibernate.Hibernate;
import org.hibernate.LockMode;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.CriteriaSpecification;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Disjunction;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.hibernate.metadata.ClassMetadata;
import org.hibernate.proxy.HibernateProxy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

/**
 * 封装Hibernate原生API的DAO泛型基类.
 * 
 * 可在Service层直接使用,也可以扩展泛型DAO子类使用.
 * 参考Spring2.5自带的Petlinc例子,取消了HibernateTemplate,直接使用Hibernate原生API.
 * 
 * @param <T> DAO操作的对象类型
 * @param <PK> 主键类型
 * 
 * @author calvin
 */
@SuppressWarnings("unchecked")
public class SimpleHibernateDao<T extends IdEntity, PK extends Serializable> {
	protected Logger logger = LoggerFactory.getLogger(getClass());
	       
	protected SessionFactory sessionFactory;

	protected Class<T> entityClass;

	/**
	 * 用于Dao层子类使用的构造函数.
	 * 通过子类的泛型定义取得对象类型Class.
	 * eg.
	 * public class UserDao extends SimpleHibernateDao<User, Long>
	 */
	public SimpleHibernateDao() {
		this.entityClass = ReflectionUtils.getSuperClassGenricType(getClass());
	}

	/**
	 * 用于用于省略Dao层, 在Service层直接使用通用SimpleHibernateDao的构造函数.
	 * 在构造函数中定义对象类型Class.
	 * eg.
	 * SimpleHibernateDao<User, Long> userDao = new SimpleHibernateDao<User, Long>(sessionFactory, User.class);
	 */
	public SimpleHibernateDao(final Class<T> entityClass) {
		this.entityClass = entityClass;
	}

	/**
	 * 取得sessionFactory.
	 */
	public SessionFactory getSessionFactory() {
		sessionFactory=(SessionFactory)ApplicationContextProvider.getBean("sessionFactory");
		return sessionFactory;
	}


	public void setSessionFactory(SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	/**
	 * 取得当前Session.
	 */
	public Session getSession() {
		return getSessionFactory().getCurrentSession();
	}

	/**
	 * 保存新增或修改的对象.
	 */
	public void save(final T entity) {
		Assert.notNull(entity, "entity不能为空");
		if (entity.getId() == null) {
			getSession().saveOrUpdate(entity);
			
			// force it flush to db. For new POJO, the ID the available then
//			getSession().flush();
		} else {
			getSession().merge(entity);
		}
		
		
	}

	public void evict(Object entity) {
		Assert.notNull(entity, "entity不能为空");
		if (ObjectPoolFactory.getInstance().isEnable()) {
			getSession().evict(entity);
		}
	}

	public void attach(Object entity) {
		Assert.notNull(entity, "entity不能为空");
		if (ObjectPoolFactory.getInstance().isEnable()) {
			getSession().lock(entity, LockMode.NONE);
		}
	}
	
	/**
	 * 删除对象.
	 * 
	 * @param entity 对象必须是session中的对象或含id属性的transient对象.
	 */
	public void delete(final T entity) {
		Assert.notNull(entity, "entity不能为空");
		getSession().delete(entity);
//		getSession().flush();
//		evict(entity);
		
		logger.debug("delete entity: {}", entity);
	}

	/**
	 * 按id删除对象.
	 */
	public void delete(final PK id) {
		Assert.notNull(id, "id不能为空");
		delete(get(id));
		
		logger.debug("delete entity {},id is {}", entityClass.getSimpleName(), id);
	}

	/**
	 * 按id获取对象.
	 */
	public T get(final PK id) {
		Assert.notNull(id, "id不能为空");
		ObjectPool pool = ObjectPoolFactory.getInstance();
		T obj = (T) pool.get(entityClass, (Long) id);
		if (obj == null) {
			obj = (T) getSession().get(entityClass, id);
			if (obj instanceof HibernateProxy) {
				evict(obj);
			}
		}

		return obj;
	}

	/**
	 *	获取全部对象.
	 */
	public List<T> getAll() {
		return find();
	}

	/**
	 *	获取全部对象,支持排序.
	 */
	public List<T> getAll(String orderBy, boolean isAsc) {
		Criteria c = createCriteria();
		if (isAsc) {
			c.addOrder(Order.asc(orderBy));
		} else {
			c.addOrder(Order.desc(orderBy));
		}
		return c.list();
	}

	/**
	 * 按属性查找对象列表,匹配方式为相等.
	 */
	public List<T> findBy(final String propertyName, final Object value) {
		Assert.hasText(propertyName, "propertyName不能为空");
		Criterion criterion = Restrictions.eq(propertyName, value);
		return find(criterion);
	}

	/**
	 * 按属性查找唯一对象,匹配方式为相等.
	 */
	public T findUniqueBy(final String propertyName, final Object value) {
		Assert.hasText(propertyName, "propertyName不能为空");

		Criterion criterion = Restrictions.eq(propertyName, value);
		return (T) createCriteria(criterion).uniqueResult();
	}

	/**
	 * 按id列表获取对象.
	 */
	public List<T> findByIds(List<PK> ids) {
		return find(Restrictions.in(getIdName(), ids));
	}

	public <X> List<X> findByNamedQuery(final String hqlName, final Object... values) {
		String hql = SqlHelper.getSql(hqlName);
		boolean nativeSql = SqlHelper.isNativeSql(hqlName);
		return createQuery(nativeSql, hql, values).list();
	}	
	
	/**
	 * 按HQL查询对象列表.
	 * 
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	public <X> List<X> find(final String hql, final Object... values) {
		return createQuery(false, hql, values).list();
	}

	public <X> List<X> findByNativeSql(final String hql, final Object... values) {
		SQLQuery query = (SQLQuery)createQuery(true, hql, values);
		query.addEntity(entityClass);
		return query.list();
	}
	
	public <X> List<X> findByNamedQuery(final String hqlName, final Map<String, ?> values) {
		String hql = SqlHelper.getSql(hqlName);
		boolean nativeSql = SqlHelper.isNativeSql(hqlName);
		return createQuery(nativeSql, hql, values).list();
	}	
	
	public <X> List<X> findByNativeSql(final String hql, final Map<String, ?> values) {
		SQLQuery query = (SQLQuery)createQuery(true, hql, values);
		query.addEntity(entityClass);
		return query.list();
	}

	/**
	 * 按HQL查询对象列表.
	 * 
	 * @param values 命名参数,按名称绑定.
	 */
	public <X> List<X> find(final String hql, final Map<String, ?> values) {
		return createQuery(false, hql, values).list();
	}

	public int delete(final String hql, final Map<String, ?> values) {
		return createQuery(false, hql, values).executeUpdate();
	}

	public <X> X findUniqueByNamedQuery(final String hqlName, final Object... values) {
		String hql = SqlHelper.getSql(hqlName);
		boolean nativeSql = SqlHelper.isNativeSql(hqlName);
		return (X) createQuery(nativeSql, hql, values).uniqueResult();
	}	
	
	/**
	 * 按HQL查询唯一对象.
	 * 
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	public <X> X findUnique(final String hql, final Object... values) {
		return (X) createQuery(false, hql, values).uniqueResult();
	}

	public <X> X findUniqueByNativeSql(final String hql, final Object... values) {
		SQLQuery query = (SQLQuery)createQuery(true, hql, values);
		query.addEntity(entityClass);
		return (X) query.uniqueResult();
	}

	public <X> X findUniqueByNamedQuery(final String hqlName, final Map<String, ?> values) {
		String hql = SqlHelper.getSql(hqlName);
		boolean nativeSql = SqlHelper.isNativeSql(hqlName);
		return (X) createQuery(nativeSql, hql, values).uniqueResult();
	}	
	
	/**
	 * 按HQL查询唯一对象.
	 * 
	 * @param values 命名参数,按名称绑定.
	 */
	public <X> X findUnique(final String hql, final Map<String, ?> values) {
		return (X) createQuery(false, hql, values).uniqueResult();
	}

	public <X> X findUniqueByNativeSql(final String hql, final Map<String, ?> values) {
		SQLQuery query = (SQLQuery)createQuery(true, hql, values);
		query.addEntity(entityClass);
		return (X) query.uniqueResult();
	}

	public <X extends IdEntity> void batchSave(List<X> entities) {
		if (entities == null || entities.size() == 0) {
			return;
		}
		
		boolean needFlush = false;
		
		Session session = getSession();
		for (int i = 0 ; i < entities.size() ; i++) {
			session.saveOrUpdate(entities.get(i)); 
			
			needFlush = true;
			
			if (i % 20 == 0) { // same as hibernate.jdbc.batch_size
				session.flush();
				session.clear();
				
				needFlush = false;
			}
		}

		if (needFlush) {
			session.flush();
			session.clear();			
		}
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 * 
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 * 
	 * @param values 数量可变的参数,按顺序绑定.
	 */
	public Query createQuery(boolean nativeSql, final String queryString, final Object... values) {
		Assert.hasText(queryString, "queryString不能为空");
		Query query = nativeSql ? getSession().createSQLQuery(queryString) : getSession().createQuery(queryString);
		if (values != null) {
			for (int i = 0; i < values.length; i++) {
				query.setParameter(i, values[i]);
			}
		}
		query.setFlushMode(FlushMode.MANUAL);
//		query.setReadOnly(true);
		return query;
	}

	/**
	 * 根据查询HQL与参数列表创建Query对象.
	 * 
	 * @param values 命名参数,按名称绑定.
	 */
	public Query createQuery(boolean nativeSql, final String queryString, final Map<String, ?> values) {
		Assert.hasText(queryString, "queryString不能为空");
		Query query = nativeSql ? getSession().createSQLQuery(queryString) : getSession().createQuery(queryString);
		if (values != null) {
			query.setProperties(values);
		}
		query.setFlushMode(FlushMode.MANUAL);
//		query.setReadOnly(true);
		
		return query;
	}

	/**
	 * 按Criteria查询对象列表.
	 * 
	 * @param criterions 数量可变的Criterion.
	 */
	public List<T> find(final Criterion... criterions) {
		return createCriteria(criterions).list();
	}

	/**
	 * 按Criteria查询唯一对象.
	 * 
	 * @param criterions 数量可变的Criterion.
	 */
	public T findUnique(final Criterion... criterions) {
		return (T) createCriteria(criterions).uniqueResult();
	}

	public Criteria createCriteria(final Criterion... criterions) {
		return createCriteria(PropertyFilter.RelationType.AND, criterions);
	}
	
	/**
	 * 根据Criterion条件创建Criteria.
	 * 
	 * 本类封装的find()函数全部默认返回对象类型为T,当不为T时使用本函数.
	 * 
	 * @param criterions 数量可变的Criterion.
	 */
	public Criteria createCriteria(PropertyFilter.RelationType rel, final Criterion... criterions) {
		Criteria criteria = getSession().createCriteria(entityClass);
		if (rel == PropertyFilter.RelationType.AND) {
			for (Criterion c : criterions) {
				criteria.add(c);
			}
		} else {
			Disjunction disjunction = Restrictions.disjunction();
			for (Criterion c : criterions) {
				disjunction.add(c);
			}
			criteria.add(disjunction);
		}
		return criteria;
	}

	/**
	 * 初始化对象.
	 * 使用load()方法得到的仅是对象Proxy, 在传到View层前需要进行初始化.
	 * 只初始化entity的直接属性,但不会初始化延迟加载的关联集合和属性.
	 * 如需初始化关联属性,可实现新的函数,执行:
	 * Hibernate.initialize(user.getRoles())，初始化User的直接属性和关联集合.
	 * Hibernate.initialize(user.getDescription())，初始化User的直接属性和延迟加载的Description属性.
	 */
	public void initEntity(T entity) {
		Hibernate.initialize(entity);
	}

	/**
	 * @see #initEntity(Object)
	 */
	public void initEntity(List<T> entityList) {
		for (T entity : entityList) {
			Hibernate.initialize(entity);
		}
	}

	/**
	 * Flush当前Session.
	 */
	public void flush() {
		getSession().flush();
	}

	/**
	 * 为Query添加distinct transformer.
	 */
	public Query distinct(Query query) {
		query.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
		return query;
	}

	/**
	 * 为Criteria添加distinct transformer.
	 */
	public Criteria distinct(Criteria criteria) {
		criteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
		return criteria;
	}

	/**
	 * 取得对象的主键名.
	 */
	public String getIdName() {
		ClassMetadata meta = getSessionFactory().getClassMetadata(entityClass);
		return meta.getIdentifierPropertyName();
	}
	
    public void execute(String hsql, final Object... values) {
        Query query = getSession().createQuery(hsql);
        if (values != null) {
	        for (int i = 0; i < values.length ; i++) {
	            query.setParameter(i, values[i]);
	        }
        }

        query.executeUpdate();
    }
    
    public void execute(String hsql, final Map<String, ?> values) {
        Query query = getSession().createQuery(hsql);
        if (values != null) {
			query.setProperties(values);
		}
		
        query.executeUpdate();
    }
    
    public String getEntityName(Object obj){
    	return getSession().getEntityName(obj);
    }
}